//
//  NSString+Helper.m
//  Consultant
//
//  Created by 朱耀春 on 17/6/19.
//  Copyright © 2017年 朱耀春. All rights reserved.
//

#import "NSString+Helper.h"
#import <CommonCrypto/CommonDigest.h>



@implementation NSString (Helper)




+ (NSString *)Hash:(NSString *)inputString{
    NSData *data = [inputString dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes,(unsigned int)data.length,digest);
    NSMutableString *outputString = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
    
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [outputString appendFormat:@"%02x",digest[i]];
    }
    return [outputString lowercaseString];
}

+(NSMutableAttributedString *)changeColorAndFontSizeWithString:(NSString *)string
                                                         range:(NSRange)range
                                                         color:(UIColor*)color
                                                    otherColor:(UIColor *)otherColor
                                                          size:(NSInteger )size
                                                     otherSize:(NSInteger )otherSize{
    //字符串改变颜色和字体大小
//    NSString *strsss = @"总价：￥115";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
    [str addAttribute:NSForegroundColorAttributeName value:color range:range];
    
    [str addAttribute:NSForegroundColorAttributeName value:otherColor range:NSMakeRange(range.length, string.length - range.length)];
    
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size] range:NSMakeRange(0, range.length )];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:otherSize] range:NSMakeRange(range.length , string.length - range.length)];
    return str;
}

+(NSString *)makeUpTwoDigitsWithIntger:(NSInteger )intger{
    NSInteger count = intger ;
    NSString * string = [NSString stringWithFormat:@"%02zd",count ];
    return string;
}

+(NSString *)theArrayIntoAJsonDataWithArray:(NSArray *)array{
    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

+(NSString *)getStringWithtime:(NSInteger)time{
    //    时间戳转时间的方法
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"dd-MM-YYYY "];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:time];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

+(NSInteger )getIntegerwithTime:(NSString *)time{
    //    设置时间显示格式:
    //    NSString* timeStr = @"2011-01-26 17:40:50";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:time]; //------------将字
    //  时间转时间戳的方法:
    NSString *timeSp = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970]];
    return [timeSp integerValue] ;
}

+(NSString *)calculatingTheTimeDifferenceWithStartTime:(NSString *)startTime
                                               endTime:(NSString *)endTime{
    
   NSInteger start = [self getIntegerwithTime:startTime];
   NSInteger end   = [self getIntegerwithTime:endTime];
    //时差
    NSInteger  shiCaInteger = end - start;
    //显示的内容计算
    NSInteger  dayInterval = shiCaInteger / (3600*24) ;
    NSInteger hourInterval = shiCaInteger / 3600;
    NSInteger minuteInterval = shiCaInteger % 3600 / 60;
    NSInteger secondInterval = shiCaInteger % 60;
    NSString * tiem = [NSString stringWithFormat:@"%@:%@:%@:%@" ,[self makeUpTwoDigitsWithIntger:dayInterval] ,[self makeUpTwoDigitsWithIntger:hourInterval],[self makeUpTwoDigitsWithIntger:minuteInterval],[self makeUpTwoDigitsWithIntger:secondInterval]];
    
    return tiem;
}

#pragma mark 获取当前时间
+(NSString*)getCurrentTimesSimplify:(BOOL)simplify{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    if (simplify) {
        currentTimeString = [currentTimeString substringToIndex:10];
    }
    return currentTimeString;
    
}

+(NSString *)GetTheFirstFewMonthsWithMonth:(NSInteger )month
                                  Simplify:(BOOL)simplify{
    //得到当前的时间
    NSDate * mydate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:0];
    [adcomps setMonth:-month];
    [adcomps setDay:0];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    if (simplify) {
        beforDate = [beforDate substringToIndex:10];
    }
    NSLog(@"---前%ld个月 =%@",month,beforDate);
    return beforDate;
}

+(NSString *)theProcessingOfTheStringWihttype:(NSInteger )type
                                       string:(NSString *)string
                                        range:(NSRange )range
                                        index:(NSInteger )index
                                 deleteString:(NSString *)deleteString{
    
    switch (type) {
        case 0:
        {
            // 1.截取字符串
            string = [string substringToIndex:index];//截取掉下标之前的字符串
        }
            break;
        case 1:
        {
            string =  [string substringFromIndex:index];//截取掉下标之后的字符串
        }
            break;
        case 2:
        {
            //2.匹配字符串
            
            string = [string substringWithRange:range];//截取范围类的字符串
        }
            break;
        
        case 3:
        {
            //将字符串中的s_ 删除
            string = [string stringByReplacingOccurrencesOfString:deleteString withString:@""];
        }
            break;
        default:
            break;
    }
    return string;
}

+(CGSize )getsTheStringHeightWithString:(NSString *)string
                                   size:(CGSize )size
                                   font:(float )fontSize{
     CGSize stringSize = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return stringSize;
}

+(id)getJSONObjectWithDataWith:(NSString *)userInfo{
    id json = [NSJSONSerialization JSONObjectWithData:[userInfo dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
    if ([json isKindOfClass:[NSArray class]]) {
        //字典
        NSLog(@"数组  %@",json);
    } else if ([json isKindOfClass:[NSDictionary class]]){
        //字典
        NSLog(@"字典  %@",json);
    }else{
        
    }
    return json;
}

+ (NSMutableAttributedString *)boldFontWithStr:(NSString *)str
                                      fontName:(NSString *)fontName
                                     fontRange:(NSRange )fontRange
                                          size:(float )size
                                   LineSpacing:(float)LineSpacing{
    //字体加粗
    NSMutableAttributedString * mutableStr =  [[NSMutableAttributedString alloc] initWithString:str];
    [mutableStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:fontName size:size] range:fontRange];
    
    if (LineSpacing > 0 ) {
        // 调整行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        // 设置文字居中
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [paragraphStyle setLineSpacing:LineSpacing];
        [mutableStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    }
    return mutableStr;
}

+ (void)callWithPhone:(NSString *)phone
                   VC:(UIViewController *)vc{
    
    NSLog(@"应该添加打电话");
    if (phone.length >= 10) {
        NSString *str2 = [[UIDevice currentDevice] systemVersion];
        if ([str2 compare:@"10.2" options:NSNumericSearch] == NSOrderedDescending || [str2 compare:@"10.2" options:NSNumericSearch] == NSOrderedSame)
        {
            NSString* PhoneStr = [NSString stringWithFormat:@"telprompt://%@",phone];
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:PhoneStr] options:@{} completionHandler:^(BOOL success) {
                    NSLog(@"phone success");
                }];
            } else {
                // Fallback on earlier versions
            }
            
        }else {
            NSMutableString* str1 = [[NSMutableString alloc]initWithString:phone];// 存在堆区，可变字符串
            if (phone.length == 10) {
                [str1 insertString:@"-"atIndex:3];// 把一个字符串插入另一个字符串中的某一个位置
                [str1 insertString:@"-"atIndex:7];// 把一个字符串插入另一个字符串中的某一个位置
            }else {
                [str1 insertString:@"-"atIndex:3];// 把一个字符串插入另一个字符串中的某一个位置
                [str1 insertString:@"-"atIndex:8];// 把一个字符串插入另一个字符串中的某一个位置
            }
            NSString * str = [NSString stringWithFormat:@"是否拨打电话\n%@",str1];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:str message: nil preferredStyle:UIAlertControllerStyleAlert];
            // 设置popover指向的item
            alert.popoverPresentationController.barButtonItem = vc.navigationItem.leftBarButtonItem;
            // 添加按钮
            [alert addAction:[UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                NSLog(@"点击了呼叫按钮10.2下");
                NSString* PhoneStr = [NSString stringWithFormat:@"tel://%@",phone];
                if ([PhoneStr hasPrefix:@"sms:"] || [PhoneStr hasPrefix:@"tel:"]) {
                    UIApplication * app = [UIApplication sharedApplication];
                    if ([app canOpenURL:[NSURL URLWithString:PhoneStr]]) {
                        [app openURL:[NSURL URLWithString:PhoneStr]];
                    }
                }
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"点击了取消按钮");
            }]];
            [vc presentViewController:alert animated:YES completion:nil];
        }
    }
}

+ (NSString *)takeOutAllTheNumbersWithString:(NSString *)str{
    NSScanner *scanner = [NSScanner scannerWithString:str];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    int number;
    [scanner scanInt:&number];
    NSString *num=[NSString stringWithFormat:@"%d",number];
    return num;
}

+ (int )takeTheNumbersWithString:(NSString *)str{
    NSCharacterSet * nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    int remainSecond =[[str stringByTrimmingCharactersInSet:nonDigits] intValue];
    return remainSecond;
}

+ (NSData *)dictionaryConversionDataWithDict:(NSDictionary *)dict{
    NSData *data= [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    return data;
}

+ (NSDictionary *)dataConversionNSDictionaryWithData:(NSData *)data{
    NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return dictionary;
}

+ (NSMutableAttributedString *)addPicturesWithString:(NSString *)str
                                               image:(UIImage *)img
                                              CGRect:(CGRect)bounds
                                               Index:(NSInteger )Index
                                         LineSpacing:(NSInteger )LineSpacing {
    
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    if (LineSpacing > 0  ) {
        // 调整行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.alignment = NSTextAlignmentRight;
        [paragraphStyle setLineSpacing:LineSpacing];
        [attriStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    }
    /**
     添加图片到指定的位置
     */
    NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
    // 表情图片
    attchImage.image = img;
    // 设置图片大小
    attchImage.bounds = bounds;
    NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
    [attriStr insertAttributedString:stringImage atIndex:Index];
    return attriStr;
}

+ (void)setRichNumberWithLabel:(UILabel*)label
                         Color:(UIColor *)color
                      FontSize:(UIFont *)font
                     alignment:(NSTextAlignment )alignment
                   LineSpacing:(NSInteger)LineSpacing{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    if (LineSpacing > 0 ) {
        // 调整行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        // 设置文字NSTextAlignment
        paragraphStyle.alignment = alignment ;
        [paragraphStyle setLineSpacing:LineSpacing];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
    }
    NSString *temp = nil;
    for(int i = 0; i < [attributedString length]; i++) {
        temp = [label.text substringWithRange:NSMakeRange(i, 1)];
        //改变字体
        if ([self isPureInt:temp]) {
            [attributedString setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                             color, NSForegroundColorAttributeName, font
                                             ,NSFontAttributeName, nil]
                                      range:NSMakeRange(i, 1)];
        }
        
        label.attributedText = attributedString;
    }
}

/**
 *此方法是用来判断一个字符串是不是整型.
 *如果传进的字符串是一个字符,可以用来判断它是不是数字
 */
+ (BOOL)isPureInt:(NSString *)string {
    NSScanner *scan = [NSScanner scannerWithString:string];
    int value;
    return [scan scanInt:&value] && [scan isAtEnd];
}

+(NSMutableAttributedString *)SetFontColorWith:(NSString *)des
                                   LineSpacing:(NSInteger )LineSpacing
                                     parameter:(NSArray *)parameter {
    //设置字体和颜色
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:des];
    // 调整行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 设置文字居中
    paragraphStyle.alignment = NSTextAlignmentCenter;
    [paragraphStyle setLineSpacing:LineSpacing];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [des length])];
    
    for (NSDictionary * data in parameter) {
        [attributedString setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:data[@"color"] ,NSForegroundColorAttributeName, KFONT(data[@"Font"], [data[@"size"] integerValue]),NSFontAttributeName, nil] range:[des rangeOfString:data[@"rang"]]];
    }
    return attributedString;
}

+(NSMutableAttributedString *)updateLineSpacing:(NSString *)des
                                    lineSpacing:(NSInteger )lineSpacing :(NSTextAlignment)textAlignment {
    //设置字体和颜色
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:des];
    // 调整行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 设置文字居中
    paragraphStyle.alignment = textAlignment;
    [paragraphStyle setLineSpacing:lineSpacing];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [des length])];
    return attributedString;
}

+(NSString *)FormattingTimeWith:(NSString *)date
                           type:(NSInteger )type{
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器(显示用)
    
    switch (type) {
        case 0:
        {
            Formatter.dateFormat = @"yyyy-MM-dd";
        }
            break;
        case 1:
        {
            Formatter.dateFormat = @"yyyy-mm-dd hh:mm:ss";
        }
            break;
        default:
            break;
    }
    NSDate* d = [Formatter dateFromString:date];
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器(显示用)
    switch (type) {
        case 0:
        {
            dateFormatter.dateFormat = @"dd MMM yy";
        }
            break;
        case 1:
        {
            dateFormatter.dateFormat = @"dd MMM yy hh:mm:ss aa";
        }
            break;
            
        default:
            break;
    }
    NSString * time  = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:d]];
    JXLog(@"%@",time);
    return time;
}

+(CGFloat)getSpaceLabelHeight:(NSString*)str
                         Font:(UIFont*)font
                        Width:(CGFloat)width
                  lineSpacing:(NSInteger )lineSpacing;{
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpacing;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    //    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

+(BOOL)isHaveEmptyString:(NSString *) string {
    NSRange range = [string rangeOfString:@" "];
    if (range.location == NSNotFound) {
        return NO;
    }else{
        return YES;
    }
}

+(BOOL)isEmptyString:(NSString *) string {
    if (!string) {
        return YES;
    }else{
        NSCharacterSet * set = [NSCharacterSet whitespaceCharacterSet];
        NSString * isString = [string stringByTrimmingCharactersInSet:set];
        if ([isString length] == 0 ) {
            return YES;
        }else{
            return NO;
        }
    }
}

+(NSString *)positiveFormat:(NSString *)text{
    if(!text || [text floatValue] == 0){
        return @"0";
    }
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    f.numberStyle = NSNumberFormatterDecimalStyle;
    NSNumber *number = [f numberFromString:text];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    [formatter setPositiveFormat:@",##0.########"];
    NSString *numStr =  [formatter stringFromNumber:number];
    return numStr;
}

+ (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = @"";
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else{
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonString;
}

+(id)getDataWithJSONObject:(NSString *)JSONObject{
    id data = [NSJSONSerialization JSONObjectWithData:[JSONObject dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
    if ([data isKindOfClass:[NSArray class]]) {
        
    } else if ([data isKindOfClass:[NSDictionary class]]){
        
    }else{
        
    }
    return data;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        NSLog(@"error：%@",error);
        return nil;
    }
    return dic;
}

+ (NSString*)getPreferredLanguage
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    NSLog(@"当前语言:%@ 所有语言：%@", preferredLang,allLanguages);
    /*"ja-CN" 日语, "en-CN" 英文缩写, "zh-Hans-CN" 简体,  "zh-Hant-CN" 繁体 */
    return preferredLang;
}

+(NSUInteger)textLength: (NSString *) text{
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength;
    return unicodeLength;
}

+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

+ (NSString *)stringFromHexString:(NSString *)hexString {
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    NSLog(@"------字符串=======%@",unicodeString);
    return unicodeString;
}

+(NSString *)removeSpaces:(NSString *)sting{
    sting = [sting stringByReplacingOccurrencesOfString:@" " withString:@""];
    return sting;
}
//千分位显示
+ (NSString *)moneyFormat:(NSString *)money{
    NSArray *moneys = [money componentsSeparatedByString:@"."];
    if (moneys.count > 2) {
        return money;
    }
    else if (moneys.count < 2) {
        return [self stringFormatToThreeBit:money];
    }
    else {
        NSString *frontMoney = [self stringFormatToThreeBit:moneys[0]];
        if([frontMoney isEqualToString:@""]){
            frontMoney = @"0";
        }
        return [NSString stringWithFormat:@"%@.%@", frontMoney,moneys[1]];
    }
}

+ (NSString *)stringFormatToThreeBit:(NSString *)string{
    if (string.length <= 0) {
        return @"".mutableCopy;
    }
    NSString *tempRemoveD = [string stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSMutableString *stringM = [NSMutableString stringWithString:tempRemoveD];
    NSInteger n = 2;
    for (NSInteger i = tempRemoveD.length - 3; i > 0; i--) {
        n++;
        if (n == 3) {
            [stringM insertString:@"," atIndex:i];
            n = 0;
        }
    }
    return stringM;
}
-(BOOL)restrictedInput:(NSString *)text shouldChangeCharactersInRange:(NSRange)range string:(NSString *)string decimals:(NSInteger)decimals{
    //对复制黏贴也有效
    int location = (int)[text rangeOfString:@"."].location;
    BOOL isHavePoint ;
    if (location > 0) {
        isHavePoint = YES; //isHavePoint 是BOOL型
    }else{
        isHavePoint = NO;
    }
    
    if ([string length] > 0) {
        unichar single = [string characterAtIndex:0];//输入的字符
        if ((single >= '0' && single <= '9') || single == '.')//输入格式正确
        {
            if ([text length] == 0) {
                if (single == '.') {
                    NSLog(@"亲，第一个数字不能为小数点");
                    return NO;
                }
                //                if (single == '0') {
                //                    NSLog(@"亲，第一个数字不能为0");
                //                    return NO;
                //                }
            }
            if (single == '.') {
                if (!isHavePoint) {
                    isHavePoint = YES;
                    return YES;
                }
                if (isHavePoint) {
                    NSLog(@"亲，您已经输入过小数点了");
                    return NO;
                }
            }else
            {
                //判断小数点的位数
                if (isHavePoint) {
                    NSRange pointRange = [text rangeOfString:@"."];
                    int location = (int)range.location - (int)pointRange.location;
                    if (location <= decimals) {
                        return YES;
                    }else{
                        NSLog(@"亲，您最多输入两位小数");
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{
            NSLog(@"亲，您输入的格式不正确");
            return NO;
        }
    }else{
        return YES;
    }
    return YES;
}




@end
